package com.github.binarywang.demo.wx.mp.service;

import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.logging.Logger;

/**
 * @ClassName HttpLogInterceptor
 * @Description TODO
 * @Author tianwanming
 * @Date 2023/3/26 16:33
 * @Version 1.0
 */
public class HttpLogInterceptor implements Interceptor {
    Logger logger = Logger.getLogger(HttpLogInterceptor.class.getName());

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request1 = chain.request();

        Headers headers = request1.headers();

        RequestBody body = request1.body();

        Buffer buffer = new Buffer();
        body.writeTo(buffer);

        String bodys = buffer.readString(Charset.forName("UTF-8"));

        logger.warning(
                "发送请求: method：" + request1.method()
                        + "\nurl：" + request1.url()
                        + "\n请求头：" + request1.headers()
                        + "\n请求参数: " + bodys);
        Response proceed = chain.proceed(request1);

        ResponseBody responseBody = proceed.body();
        BufferedSource source = responseBody.source();
        String s = source.readString(Charset.forName("UTF-8"));
        logger.warning(
                "收到响应: code:" + proceed.code()
                        + "\n请求url：" + proceed.request().url()
                        + "\n请求body：" + bodys
                        + "\nResponse: " + s);

        return proceed;
    }
}
